from django.http import JsonResponse
import json
from ..models import Config, News, Notice, Paper
from django.db.models import Case, When


def config_handle(request):
    if request.method == 'GET':
        request.params = request.GET
    else:
        request.params = json.loads(request.body)
    action = request.params.get('action')

    if action in action_handler_dict_all:  # 无需登录
        return action_handler_dict_all[action](request)
    if action in action_handler_dict_mg:  # 只有管理员才能操作
        if not request.user.is_authenticated:  # 要登录
            return JsonResponse({'ret': 1, 'msg': '未登录'}, json_dumps_params={'ensure_ascii': False})
        if request.user.usertype not in [1, 1000]:
            return JsonResponse({'ret': 1, 'msg': '非管理员'}, json_dumps_params={'ensure_ascii': False})
        return action_handler_dict_mg[action](request)
    return JsonResponse({'ret': 1, 'msg': 'action参数错误'})

def setconfig(request):
    try:
        name=request.params.get('name')
        value=request.params.get('value')
        record = Config.objects.filter(name=name)
        if record.exists():
            record.update(value=value)
        else:
            record.create(name=name, value=value)
        return JsonResponse({'ret': 0})
    except Exception as e:
        return JsonResponse(
            {'ret': 1, 'msg': str(e)})

def getconfig(request):
    try:
        name = request.params.get('name')
        record = Config.objects.get(name=name)
        return JsonResponse({'ret': 0, 'value': record.value})
    except Config.DoesNotExist:
        return JsonResponse({"ret": 0, "value": ''})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

def gethomepagebyconfig(request):
    try:
        info = {"news": [], "notice": [], "paper": []}
        value = Config.objects.get(name='homepage').value
        value = json.loads(value)
        newsid = value['news']
        news_order = Case(*[When(id=id, then=idx) for idx, id in enumerate(newsid)])
        news = News.objects.filter(id__in=newsid).values(
            'id', 'pubdate', 'author', 'author__realname', 
            'title', 'status').order_by(news_order)
        noticeid = value['notice']
        notice_order = Case(*[When(id=id, then=idx) for idx, id in enumerate(noticeid)])
        notice = Notice.objects.filter(id__in=noticeid).values(
            'id', 'pubdate', 'author', 'author__realname', 
            'title', 'status').order_by(notice_order)
        paperid = value['paper']
        paper_order = Case(*[When(id=id, then=idx) for idx, id in enumerate(paperid)])
        paper = Paper.objects.filter(id__in=paperid).values(
            'id', 'pubdate', 'author', 'author__realname', 
            'title', 'status').order_by(paper_order)
        info['news'] = list(news)
        info['notice'] = list(notice)
        info['paper'] = list(paper)
        return JsonResponse({"ret": 0, "info": info})
    except Config.DoesNotExist:
        return JsonResponse({"ret": 0, "info": info})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})
            

action_handler_dict_mg = {
    'set': setconfig,
    'get': getconfig,
}

action_handler_dict_all = {
    'gethomepagebyconfig': gethomepagebyconfig,
}